<?php

namespace api\modules\v1\models;

use api\common\models\Common;
use api\func\func;
use Yii;
use yii\data\Pagination;

class Withdraw extends Common
{

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return '{{%withdraw_app}}';
    }


    public function rules()
    {
        return [
            [['userid','withdraw_type','account','money','status'], 'required','message'=>'{attribute}不能为空'],
            [['userid','withdraw_type','status'], 'integer'],
            [['account'], 'string','max' => 100 ],
            ['money', 'double'],
            ['money','match','pattern'=>'/^[0-9]+(.[0-9]{1,2})?$/'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'userid' => Yii::t('app', '用户有ID'),
            'withdraw_type' => Yii::t('app', '帐户类型'),
            'account' => '提现帐户',
            'money' => Yii::t('app', '提取金额'),
            'status' => Yii::t('app', '提取状态')
        ];
    }

    public function getList(){
        $uid = Yii::$app->user->identity->id;
        $query = (new \yii\db\Query())
            ->select(['b.nickname','b.phone','a.money','a.time','a.withdraw_type','a.status'])
            ->from('{{%withdraw_app}} as a')
            ->join('LEFT JOIN','{{%user_app}} as b','a.userid=b.id')
            ->where(['a.userid'=>$uid]);

        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];

        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('time desc')
            ->all();

        $this->serializePagination($pagination);


        foreach($data as &$value){
            $value['money'] = number_format($value['money'],2);
            $value['nickname'] = $value['nickname'] !='' ? $value['nickname']: func::replace_phone($value['phone']);
            unset($value['phone']);
        }

        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;

        return $_data;
    }

}
